const express = require('express')

const request = require('request')
var path = require("path");
//1.导入模块
const xmlparser = require('express-xml-bodyparser');
const bodyParser = require('body-parser');
// 微信加密签名
const crypto = require('crypto');
// 路由模块
const filingRouter = require('./filing')
const app = express()


// 允许跨域
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  // res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", ' 3.2.1')
  if (req.method === "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});
app.use(xmlparser());
app.use("/frontend/index.html", express.static(path.join(__dirname, "./staticPages/dist/index.html"))) //邀请页面
app.use("/frontend/redirect", express.static(path.join(__dirname, "./staticPages/redirectPages.html"))) //重定向页面
app.use("/frontend/skipminiprogram", express.static(path.join(__dirname, "./staticPages/nextSkipPages.html"))) //跳转小程序页面
// 格式化参数
app.use(express.json())
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());
app.use((req, res, next) => {
  res.setHeader('Content-Security-Policy', "font-src 'self' http://localhost:9090;");
  next();
});
// 建档接口
app.use('/frontend/filing/v1', filingRouter)

const baseURl = 'http://localhost:8101/api';
app.use(express.static('testtest'));
// vue打包文件
// css
app.get('/frontend/appb41cbdee.css', function (req, res) {
  res.type('text/css');
  res.sendFile(__dirname + '/staticPages/dist/css/app.a2c530ac.css');
});
app.get('/frontend/chunk-vendors9ddc568c.css', function (req, res) {
  res.type('text/css');
  res.sendFile(__dirname + '/staticPages/dist/css/chunk-vendors.9ddc568c.css');
});
// js
app.get('/frontend/appc5a747a8.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/app.522b44f6.js');
});
app.get('/frontend/248.bbe1179a.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/248.bbe1179a.js');
});
app.get('/frontend/623.f491ecbe.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/623.f491ecbe.js');
});
app.get('/frontend/chunk-vendorsbd3c7cf7.js', function (req, res) {
  res.type('text/javascript');
  res.sendFile(__dirname + '/staticPages/dist/js/chunk-vendors.5314a278.js');
});
// 小程序校验文件目录
app.get('/frontend/MP_verify_7EsaE8XInVGwUvux.txt', function (req, res) {
  res.sendFile(__dirname + '/MP_verify_7EsaE8XInVGwUvux.txt');
});
app.get('/frontend/RKDK342248.txt', function (req, res) {
  res.sendFile(__dirname + '/RKDK342248.txt');
});
app.get('/frontend/base64data.json', function (req, res) {
  res.sendFile(__dirname + '/base64.json');
});
app.get('/frontend/login', function (req, res) {
  res.send('Hello World!');
});
// 公众号接口
// 获取公众号的openid
app.get('/frontend/officialAccounts', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${req.query.code}&grant_type=authorization_code`,
    function (err, response, body) {
      res.send(body)
    }
  )
})
// 获取公众号的unionId
app.get('/frontend/officialAccountsUnionId', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  let access_token = ''
  request(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
    function (err, response, body) {
      access_token = body.access_token
      request(`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${access_token}&openid=${req.query.openId}`,
        function (err, response, body) {
          res.send(body)
        })
    }
  )
})
// get登录接口获取openid
app.get('/frontend/secondTrialLogin', (req, res) => {
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=wx5829252f188052a7&secret=02a1995f8c318d3c38455144c6bcaa1c&js_code=${req.query.code}&grant_type=authorization_code`,
    function (err, response, body) {
      res.send(body)
    })
})

// 通过access_token获取公众号的openid
app.get('/frontend/sofficialAccountAccessOpenid', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
    function (err, response, body) {
      let access_token = JSON.parse(body).access_token
      request(`https://api.weixin.qq.com/cgi-bin/user/get?access_token=${access_token}`, function (err, response, body) {
        res.send(body)
      })
    })
})
// 公众号获取openid
app.get('/frontend/sofficialAccount', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${req.query.code}&grant_type=authorization_code`,
    function (err, response, body) {
      console.log(body, '---------数据')
      res.send(body)
    })
})
// 健康管理申请
app.use("/frontend/healthManagement", express.static(path.join(__dirname, "./staticPages/healthManagementView.html")))
app.use("/frontend/test", express.static(path.join(__dirname, "./staticPages/test.html")))


// 公众号推送消息
app.get('/frontend/api/OfficialAccounts', (req, res) => {
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  let serviceOfficialAccountOpenid = ''
  let requestId = req.query.requestId
  let familyMemberId = req.query.familyMemberId
  request(baseURl + `/userInfo/wechat?familyMemberId=${familyMemberId}`, function (err, response, body) {
    serviceOfficialAccountOpenid = JSON.parse(body).data.serviceOfficialAccountOpenid
    console.log(JSON.parse(body), '----------------JSON.parse(body)')
    request(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
      function (err, response, body) {
        let access_token = JSON.parse(body).access_token
        console.log(JSON.parse(body), '------access_token');
        let params = {
          "touser": serviceOfficialAccountOpenid,
          "template_id": "6c55gHsAVSNHeKEawv3BZd_mgY0NJTCE4LYlmcNMzjY",
          "url": `https://zg.particlesoft.info/frontend/healthManagement?requestId=${requestId}&familyMemberId=${familyMemberId}`,
          // "miniprogram": {
          //   "appid": appid,
          //   "pagepath": "https://zg.particlesoft.info/frontend/inviteView"
          // },
          "data": {
            "first": {
              "value": "我是first！",
              "color": "#173177"
            },
            "keyword1": {
              "value": "keyword1",
              "color": "#173177"
            },
            "keyword2": {
              "value": "keyword2",
              "color": "#173177"
            },
            "keyword3": {
              "value": "keyword3",
              "color": "#173177"
            },
            "remark": {
              "value": "备注",
              "color": "#173177"
            }
          },
        }
        request({
          url: `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`,
          method: "POST",
          json: true,
          body: params
        }, (err, rep, body) => {
          if (err) {
            console.log("request 请求post 出现错误 err : ", err);
            return false;
          }
          // body表示返回的数据
          if (body) {
            // 请求成功
            res.send(body)
          }
        })
      })
  })
})

// 验证消息是否来自微信
function checkSignature(signature, timestamp, nonce) {
  const token = 'particlesoft'; // 这里填写在公众平台设置的令牌
  const tmpArr = [token, timestamp, nonce].sort();
  const tmpStr = tmpArr.join('');
  // 使用sha1加密算法
  const sha1 = crypto.createHash('sha1');
  sha1.update(tmpStr);
  const encryptStr = sha1.digest('hex');
  if (encryptStr === signature) {
    return true;
  } else {
    return false
  }
}

// 微信监听用户是否关注公众号接口
app.post('/frontend/', (req, res) => {
  console.log(req.headers['content-type']);
  const signature = req.query.signature;
  const timestamp = req.query.timestamp;
  const nonce = req.query.nonce;
  if (checkSignature(signature, timestamp, nonce)) {
    console.log(signature, timestamp, nonce, '====== 签名');
    const txMessage = req.query;
    const openId = txMessage.openid
    const appid = 'wxdc7ed0f21b5d80bf'
    const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
    request(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`, function (err, response, body) {
      let access_token = JSON.parse(body).access_token
      request(`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${access_token}&openid=${openId}&lang=zh_CN`, function (err, response, body) {
        let offunionId = JSON.parse(body).unionid
        console.log(offunionId, "offunionId=================");
        console.log(JSON.parse(body), "aaaaaaaaaaaaaaaaaa=================");
        if (JSON.parse(body).subscribe == 1) {
          request({
            url: baseURl + '/userInfo/wechat',
            method: "POST",
            json: true,
            body: {
              serviceOfficialAccountOpenid: openId,
              miniprogramOpenid: '',
              unionid: offunionId
            }
          }, (err, rep, body) => {
            if (err) {
              console.log("request 请求post 出现错误 err : ", err);
              res.send("request 请求post 出现错误 err : ", err)
              return false;
            }
            // body表示返回的数据
            if (body) {
              // 请求成功
              console.log(body)
              res.send('success');
            }
          })
        } else {
          res.send('success');
        }

      })
    })
    console.log(txMessage, '======xml');
  } else {
    res.send('err');
  }
});
// 微信监听用户是否关注公众号接口
app.get('/frontend/', (req, res) => {
  // const contentType = req.headers['content-type'];
  const signature = req.query.signature;
  const timestamp = req.query.timestamp;
  const nonce = req.query.nonce;
  const echostr = req.query.echostr;
  if (checkSignature(signature, timestamp, nonce)) {
    // 验证通过，可以处理接收到的消息
    console.log(signature, timestamp, nonce, '====== 签名');
    res.send(echostr);
  } else {
    // 验证失败，不处理消息
    res.send('err');
  }
});

// 小程序消息推送
app.post('/frontend/miniProgramMessages', (req, res) => {
  // console.log(req.headers['content-type']);
  // console.log(req.query)
  const appid = 'wxdc7ed0f21b5d80bf'
  const appsecret = 'c7dbd345efa677d3b121040085b66fb3'
  request(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
    function (err, response, body) {
      const access_token = JSON.parse(body).access_token
      console.log(access_token, 'access_tocken')
      console.log(req.body.openId, 'openid')
      const params = {
        touser: req.body.openId,
        lang: "zh_CN",
        data: {
          time1: {
            value: "家人"
          },
          thing2: {
            value: "老张"
          },
          thing3: {
            value: "老张"
          },
          thing4: {
            value: "老张"
          },
        },
        miniprogram_state: "trial",
        template_id: 'y-JcSlf8kgU58k-b7wS9nDep11q-2q6nrK6gccNlufY',
      }
      console.log('==============access_token', access_token)
      request({
        url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`,
        method: 'POST',
        json: true,
        body: params,
      }, function (err, req, body) {
        if (err) {
          console.log('错误 request post', err)
          return false
        }
        if (body) {
          console.log(body);
          res.send(body)
        }
      })

    })
})
app.get('/frontend/miniProgramMessage', (req, res) => {
  console.log(req.query)
  const signature = req.query.signature;
  const timestamp = req.query.timestamp;
  const nonce = req.query.nonce;
  const echostr = req.query.echostr;
  if (checkSignature(signature, timestamp, nonce)) {
    // 验证通过，可以处理接收到的消息
    console.log(signature, timestamp, nonce, '====== 签名');
    res.send(echostr);
  } else {
    // 验证失败，不处理消息
    res.send('err');
  }
})

app.listen(9090, () => {
  console.log('服务器开启');
})